﻿using Fly.Domain.Authentication;
using Fly.Domain.Extension;
using Fly.Domain.Models;
using Fly.Domain.Services;
using Fly.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Fly.Domain.Services.Messaging;
using System.IO;
using System.Net;
using Fly.Domain.Email;

namespace Fly.Web.Controllers
{
    public class AccountController : BaseController
    {
        #region Views
        // GET: Account
        public ActionResult Index()
        {
            var user = new UserService().GetUserInfo(CurrentUserId);
            ViewBag.MyVisitors = new VisitorService().GetTopTwelve(CurrentUserId);
            return View(user);
        }
        //登录
        [AllowAnonymous]
        public ActionResult Login()
        {
            //如果已经登录，直接跳转至主页
            if (HttpContext.User.Identity.IsAuthenticated)
                return RedirectToAction("Index", "Account");

            var cookie = Request.Cookies["Email"];
            if (cookie != null)
            {
                ViewBag.Email = cookie.Value;
            }

            return View();
        }
        //注册 
        [AllowAnonymous]
        public ActionResult Register()
        {
            return View();
        }
        //忘记密码
        [AllowAnonymous]
        public ActionResult Forget()
        {
            return View();
        }
        //帐号设置
        public ActionResult Set()
        {
            var user = new UserService().GetUserInfo(CurrentUserId);
            return View(user);
        }
        //用户主页
        [AllowAnonymous]
        public ActionResult Home(int userId)
        {
            var user = new UserService().GetUserInfo(userId);

            var posts = new PostService().GetPagePostsByFilter(new GetPagePostsRequest(1, 30) { UserId = userId });
            if (posts.IsSuccess)
                ViewBag.MyPosts = posts.Pages.Items; //最近求解
            var answers = new CommentService().GetPageCommentsByUserId(1, 30, userId);
            if (answers.IsSuccess)
                ViewBag.MyAnswers = answers.Pages.Items;//最近回答 最新的30条
            if (CurrentUserId != -1 && userId != CurrentUserId)//证明有登录的 且不是自己访问自己则更新访客记录
            {
                new VisitorService().AddVisitor(new Visitor
                {
                    VisitorUserId = CurrentUserId,
                    UserId = userId,
                    LastTime = DateTime.Now
                });
            }

            return View(user);
        }
        //搜索@
        [AllowAnonymous]
        public ActionResult Jump(string nickname)
        {
            var user = new UserService().GetUserByNickname(nickname);
            if (user == null)
                return Redirect("~/error/404");

            var posts = new PostService().GetPagePostsByFilter(new GetPagePostsRequest(1, 30) { UserId = user.Id });
            if (posts.IsSuccess)
                ViewBag.MyPosts = posts.Pages.Items; //最近求解
            var answers = new CommentService().GetPageCommentsByUserId(1, 30, user.Id);
            if (answers.IsSuccess)
                ViewBag.MyAnswers = answers.Pages.Items;//最近回答 最新的30条
            if (CurrentUserId != -1 && user.Id != CurrentUserId)//证明有登录的 且不是自己访问自己则更新访客记录
            {
                new VisitorService().AddVisitor(new Visitor
                {
                    VisitorUserId = CurrentUserId,
                    UserId = user.Id,
                    LastTime = DateTime.Now
                });
            }

            return View("Home",user);
        }
        //激活邮箱
        public ActionResult Activate()
        {
            var user = new UserService().GetUserInfo(CurrentUserId);
            return View(user);
        }
        //我的消息 
        public ActionResult Message()
        {
            return View();
        }
        //注销登录
        public ActionResult LogOut()
        {
            new AspFormsAuthentication().SignOut();
            return RedirectToAction("Index", "Home");
        }
        //验证邮箱
        [AllowAnonymous]
        public ActionResult EmailValidateResult(string token = "")
        {
            var response = new UserService().EmailValidate(token);
            if(response.IsSuccess)
                new AspFormsAuthentication().SignOut();//验证成功后需要重新登录
            return View(response);
        }
        //发送激活邮箱
        public ActionResult SendActivate()
        {
            var response = new UserService().SendActivateEmail(CurrentAccount);
            return JsonResultForFly(response.IsSuccess ? 0 : 1, response.Message);
        }
        #endregion


        #region Handler
        ///user/upload/
        //上传图片
        [HttpPost]
        public ActionResult Upload(HttpPostedFileBase f)
        {
            try
            {
                var files = Request.Files;
                if (files.Count == 0)
                    return Json(new
                    {
                        status = 1,
                        msg = "请选择要修改的头像"
                    });
                var curFile = files[0];
                if ((curFile.ContentLength / 1024) > 30)
                {
                    return Json(new
                    {
                        status = 1,
                        msg = "请选择小于30KB的图片."
                    });
                }

                //获取保存路径
                var filesUrl = Server.MapPath("~/Uploads/HeadPortraits/");
                if (Directory.Exists(filesUrl) == false)//路径不存在则创建
                    Directory.CreateDirectory(filesUrl);
                var fileName = Path.GetFileName(curFile.FileName);
                //文件后缀名
                var filePostfixName = fileName.Substring(fileName.LastIndexOf('.'));
                //新文件名
                var newFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + filePostfixName;
                var path = Path.Combine(filesUrl, newFileName);
                //保存文件
                curFile.SaveAs(path);

                var newPath = "/Uploads/HeadPortraits/" + newFileName;

                new UserService().UpdateHeadPortrait(newPath, CurrentUserId);


                return Json(new
                {
                    status = 0,
                    msg = "上传成功",
                    url = newPath
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    status = 1,
                    msg = "上传失败、错误信息：" + ex.Message
                });
            }
        }
        //登录
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AllowAnonymous]
        public ActionResult Login(LoginModel model)
        {
            if (model == null)
                return JsonResult(false, "请勿传递非法参数，请刷新重试！");

            //验证验证码是否正确
            var sessionVerifyCode = Session["VerifyCode"];
            if (sessionVerifyCode == null || model.Vercode != sessionVerifyCode.ToString())
                return JsonResult(false, "验证码输入错误！");

            var userService = new UserService();

            var entity = userService.Login(model.Email);
            if (entity == null)
            {
                return JsonResult(false, "用户不存在。");
            }
            if (entity.Password != model.Pass.ToMd5())
            {
                return JsonResult(false, "用户名或密码输错了呢。");
            }
            if (entity.IsDisabled)
            {
                return JsonResult(false, "你的帐号已被封，请联系管理员。");
            }
            //记录登录日志
            //new LoginLogService().Insert(new LoginLog
            //{
            //    UserId = entity.Id,
            //    Ip = WebHelper.GetIp(),
            //    CreateTime = DateTime.Now,
            //    UserAgent = Request.UserAgent
            //});

            //重置错误次数
            //Session["PwdErrorCount"] = null;
            //保存身份票据
            new AspFormsAuthentication().SetAuthenticationToken(entity.Email + "$" + entity.Id + "$" + entity.EmailConfirmed + "$" + entity.IsAdmin);
            //保存登录名
            //if (model.RememberMe)
            //{
            HttpCookie cookie = new HttpCookie("Email");
            cookie.Value = entity.Email;
            cookie.Expires = DateTime.Now.AddDays(5);

            Response.Cookies.Set(cookie);
            //}
            entity.Password = "";
            return JsonResult(true, "登录成功。", new { user = entity });
        }
        //注册
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AllowAnonymous]
        public ActionResult Register(RegisterModel model)
        {
            if (model == null)
                return JsonResult(false, "请勿传递非法参数，请刷新重试！");

            var sessionVerifyCode = Session["VerifyCode"];
            if (sessionVerifyCode == null || model.Vercode != sessionVerifyCode.ToString())
                return JsonResult(false, "验证码输入错误，请刷新重试！");

            var service = new UserService();
            if (service.CheckEmailIsExists(model.Email))
                return JsonResult(false, "该邮箱已被注册！");
            if (service.CheckNicknameIsExists(model.Nickname))
                return JsonResult(false, "该昵称已被使用！");


            var entity = new User
            {
                Email = model.Email,
                Password = model.Pass.ToMd5(),
                Nickname = model.Nickname,
                Gender = Gender.Man,
                HeadPortrait = GetRandomFileName(),//头像先留空，后面再处理
                VipLevel = -1,
                CreateTime = DateTime.Now,
                Integral = 200,//注册时送200积分
                EmailIsUpdate = true
            };

            var response = service.Register(entity);


            return JsonResult(response.IsSuccess, response.Message);
            //return JsonResultForFly(response.IsSuccess ?0:1,response.Message,"/user/login/");
        }
        //设置
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Set(SetModel model)
        {
            if (model == null || model.Id == 0)
                return JsonResultForFly(1, "请勿传递非法参数，请刷新重试！");

            var service = new UserService();

            var user = service.GetUserInfo(CurrentUserId);
            if (user.Email != user.Email && !user.EmailIsUpdate)
                return JsonResultForFly(1, "请先验证邮箱.");
            if (service.CheckEmailIsExists(model.Email, CurrentUserId))
                return JsonResultForFly(1, "邮箱已存在.");
            if (service.CheckNicknameIsExists(model.Nickname, CurrentUserId))
                return JsonResultForFly(1, "昵称已存在.");

            user.Nickname = model.Nickname;
            user.Gender = (Gender)model.Gender;
            user.City = model.City;
            user.Sign = model.Sign;

            var response = service.UpdateUser(user);


            return JsonResultForFly(response.IsSuccess ? 0 : 1, response.Message);
        }
        //修改密码
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Repass(RepassModel model)
        {
            if (model == null)
                return JsonResultForFly(1, "请勿传递非法参数，请刷新重试！");

            var service = new UserService();

            var user = service.GetUserInfo(CurrentUserId);
            if (user.Password != model.NowPass.ToMd5())
                return JsonResultForFly(1, "原密码输入错误，请重试！");

            user.Password = model.Pass.ToMd5();

            var response = service.UpdateUser(user);

            if (response.IsSuccess)
                return JsonResultForFly(0, "修改成功，下次登录生效！", "/user/");

            return JsonResultForFly(1, "修改失败，请重试！");
        }
        #endregion


        #region Private Methods
        /// <summary>
        /// 在指定文件夹内获取随机一个文件
        /// </summary>
        /// <returns></returns>
        private string GetRandomFileName()
        {
            var path = Server.MapPath("~/Images/DefaultHeadPortraits/");//文件夹路径
            DirectoryInfo dir = new DirectoryInfo(path);
            if (dir.Exists)
            {
                FileInfo[] fiList = dir.GetFiles();

                Random ran = new Random();
                int n = ran.Next(fiList.Length - 1);

                return "/Images/DefaultHeadPortraits/" + fiList[n].Name;

            }
            return "";
        }
        #endregion
    }
}